/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-06-15 15:56:22
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-07-27 16:47:56
 * @FilePath: \ems_neutral_app\lib\pages\Devices\Scan\ScanPage.dart
 * @Description: 扫描
 */
import 'package:ems_neutral_app/base/SilScaffold.dart';
import 'package:ems_neutral_app/pages/Mine/Language/LanguageController.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/toast/SilToastExtends.dart';
import 'package:flutter/material.dart';
import 'package:images_picker/images_picker.dart';
import 'package:scan/scan.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';

import '../../../utils/permission/PermissionUtils.dart';

class ScanPage extends StatefulWidget {
  const ScanPage({super.key});

  @override
  State<ScanPage> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage>
    with RouteAware, WidgetsBindingObserver {
  ScanController controller = ScanController();
  LanguageController _languageController = LanguageController();
  bool _isPromptEnglish = true;

  /// 手电筒
  bool _flashlightOn = false;

  @override
  void initState() {
    super.initState();

    _isPromptEnglish = _languageController.isPromptEnglish();
  }

  void didPopNext() {
    controller.resume();
  }

  void didPush() {
    controller.resume();
  }

  void didPop() {
    controller.pause();
  }

  void didPushNext() {
    controller.pause();
  }

  @override
  void dispose() {
    controller.pause();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // app重新进入前台时
      controller.resume();
    }
    super.didChangeAppLifecycleState(state);
  }

  /// 返回将扫描结果带回去
  rebackHandler(qrcode) {
    if (qrcode == null) {
      SilToastExtends.toastMsg(_isPromptEnglish ? "Recognition failure！": "识别失败！");
      return;
    }

    Future.delayed(Duration(microseconds: 300)).then((value) {
      Navigator.pop(context, qrcode);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      sideMargin: 0,
      title: _isPromptEnglish ? 'Scan' :'扫描',
      trailingWidget: rightPhotoAlbumBtn(),
      body: mainWidget(),
    );
  }

  rightPhotoAlbumBtn() {
    return SilButton(
      title: _isPromptEnglish ? 'Photo Album' :'相册',
      titleColor: ColorUtils.color_font_main,
      padding: EdgeInsets.only(right: 20.w),
      onTapFunc: () async {
        /// 申请相册权限
        bool value = await PermissionUtils.permission_photo();
        if (value == false) return;

        String? _qrcode;
        List<Media>? res = await ImagesPicker.pick();
        if (res != null) {
          _qrcode = await Scan.parse(res[0].path);
        }

        /// 有没有结果都要返回
        rebackHandler(_qrcode);
      },
    );
  }

  mainWidget() {
    return SafeArea(
      top: true,
      bottom: true,
      child: Stack(
        alignment: Alignment.center,
        children: [
          ScanView(
            controller: controller,
            scanAreaScale: .6,
            scanLineColor: ColorUtils.color_theme,
            onCapture: (qrcode) {
              /// 有没有结果都要返回
              rebackHandler(qrcode);
            },
          ),
          Positioned(
              bottom: 50.w,
              child: SilButton(
                imgPath: _flashlightOn
                    ? 'imgs/common/common_flashlight_on.png'
                    : 'imgs/common/common_flashlight_off.png',
                height: 32.w,
                width: 32.w,
                onTapFunc: () {
                  controller.toggleTorchMode();
                  setState(() {
                    _flashlightOn = !_flashlightOn;
                  });
                },
              )),
        ],
      ),
    );
  }
}
